package com.adaptiveAgingAdmin.utils;

import com.adaptiveAgingAdmin.code.Code;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;

/**
 * JWT工具类,可以根据用户id,便捷地生成accessToken和refreshToken
 *
 * @author 张涛
 */
public class JwtUtil{

    private static final String secret= "*"+Code.TOKEN_SECRET+"*";

    /**
     *
     * @param id Long
     * @return
     */
    public static String getRefreshToken(Long id){
        return JWT.create()
                .withClaim("id",id)
                .withExpiresAt(new Date(System.currentTimeMillis()+Code.TOKEN_KEEP_LOGIN_TIME))
                .sign(Algorithm.HMAC256(secret));
    }

    /**
     *
     * @param id Long
     * @return
     */
    public static String getAccessToken(Long id){
        return JWT.create()
                .withClaim("id",id)
                .withExpiresAt(new Date(System.currentTimeMillis() +
                        (Code.TOKEN_KEEP_LOGIN_TIME > Code.TOKEN_REFRESH_TIME ?
                        Code.TOKEN_REFRESH_TIME : Code.TOKEN_KEEP_LOGIN_TIME)))
                .sign(Algorithm.HMAC256(secret));
    }

    /**
     *
     * @param id Long
     * @param time Long
     * @return
     */
    public static String getToken( Long id , Long time ){
        return JWT.create()
                .withClaim("id",id)
                .withExpiresAt(new Date(System.currentTimeMillis()+time))
                .sign(Algorithm.HMAC256(secret));
    }

    /**
     * 解析token,返回id
     * @param token String
     * @return
     */
    public static Long parseToken(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        return verify.getClaim("id").asLong();
    }
}
